//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

use git2::{Config, Error};
use serde::Serialize;
use std::path::PathBuf;

#[derive(Serialize, Clone, Debug)]
struct ConfigItem {
    name: String,
    value: String,
}

pub fn exec(git_path: PathBuf, local: &bool) -> Result<(), Error> {
    let cfg = if *local {
        let mut cfg_path = git_path.clone();
        cfg_path.push(".git");
        cfg_path.push("config");
        Config::open(&cfg_path)
    }else{
        Config::open_default()
    };
    if cfg.is_err() {
        return Err(cfg.err().unwrap());
    }
    let cfg = cfg.unwrap();
    let entrys = cfg.entries(None);
    if entrys.is_err() {
        return Err(entrys.err().unwrap());
    }
    let mut entrys = entrys.unwrap();
    let mut ret_list = Vec::new();
    while let Some(entry) = entrys.next() {
        if entry.is_err() {
            return Err(entry.err().unwrap());
        }
        let entry = entry.unwrap();
        let name = String::from(entry.name().unwrap_or(""));
        let value = String::from(entry.value().unwrap_or(""));
        ret_list.push(ConfigItem {
            name: name,
            value: value,
        })
    }
    println!("{}", serde_json::to_string(&ret_list).unwrap());
    return Ok(());
}
